package com.macro.mall.portal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.common.util.DateUtil;
import com.macro.mall.common.util.StringIf;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.config.MallSecurityConfig;
import com.macro.mall.portal.config.MyBatisConfig;
import com.macro.mall.portal.dao.PortalProductDao;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.dto.UmsCheckInDto;
import com.macro.mall.portal.dto.UmsMemberDto;
import com.macro.mall.portal.service.PortalStoreService;
import com.macro.mall.portal.service.UmsMemberCacheService;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.service.UmsStoreCacheService;
import com.macro.mall.security.util.JwtTokenUtil;
import local.com.quyum.aliyun.aliyunsms.service.ISmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 会员管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private UmsMemberCacheService memberCacheService;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private ISmsService smsService;
    @Autowired
    private PortalStoreService portalStoreService;
    @Autowired
    private UmsCheckInIntegrationMapper checkInMapper;
    @Autowired
    private UmsStoreCacheService cacheService;
    @Autowired
    private UmsIntegrationChangeHistoryMapper integrationChangeHistoryMapper;
    @Autowired
    private PortalProductDao portalProductDao;
    @Autowired
    private UmsAgentCoordMapper agentCoordMapper;
    @Autowired
    private OmsOrderReturnApplyMapper returnApplyMapper;
    @Autowired
    private UmsMemberLevelChangeHistoryMapper changeHistoryMapper;
    @Value("${redis.key.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;
    @Autowired
    private RedisService redisService;

    @Value("${redis.database}")
    private String REDIS_DATABASE;
    @Value("${redis.key.member}")
    private String REDIS_KEY_MEMBER;

    @Override
    public UmsMember getByUsername(String username) {
        UmsMember member = memberCacheService.getMember(username);
        if (member != null) return member;
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    @Override
    public UmsMember getByUsernameOrPhone(String username) {
        UmsMember member = memberCacheService.getMember(username);
        if (member != null) return member;
        UmsMemberExample example = new UmsMemberExample();
        UmsMemberExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(username));
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public String register(String realName, String password, String telephone, String authCode,Long agentId) {
        String result = "";
        //验证验证码
        CommonResult commonResult = verifyAuthCode(authCode, telephone);
        if(commonResult.getCode()== ResultCode.SUCCESS.getCode()){
            //查询是否已有该用户
            UmsMemberExample example = new UmsMemberExample();
            example.createCriteria().andUsernameEqualTo(telephone);
            example.or(example.createCriteria().andPhoneEqualTo(telephone));
            List<UmsMember> umsMembers = memberMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(umsMembers)) {
                Asserts.fail("该用户已经存在");
            }

            //没有该用户进行添加操作
            UmsMember umsMember = new UmsMember();
            if(agentId!=null){
                UmsMember agent = this.memberMapper.selectByPrimaryKey(agentId);
                if(agent.getType().equals(1)){
                    umsMember.setStoreId(agent.getStoreId());
                    umsMember.setStoreUserId(agent.getStoreUserId());
                    umsMember.setAgentId(agent.getId());
                }
            }
//        umsMember.setStoreId(Long.valueOf(8));
//        umsMember.setStoreUserId(Long.valueOf(3));
            umsMember.setUsername(telephone);
            umsMember.setPhone(telephone);
            umsMember.setRealName(realName);
            umsMember.setPassword(passwordEncoder.encode(password));
            umsMember.setCreateTime(new Date());
            umsMember.setStatus(1);
            umsMember.setType(0);//注册的为用户0
            umsMember.setCheckIn(getNewCheckIn());//注册用户设置签到
            umsMember.setIcon("https://mei-rang.oss-cn-beijing.aliyuncs.com/img/2020/10/28/8c1ad68c572d4a33a3466b5e5eaf92d5579d5a59-d41f-4578-bd22-0c908b6153df.jpg");
            //获取默认会员等级并设置
//        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
//        levelExample.createCriteria().andDefaultStatusEqualTo(1);
//        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
//        if (!CollectionUtils.isEmpty(memberLevelList)) {
//            umsMember.setMemberLevelId(memberLevelList.get(0).getLevel());
//        }
            umsMember.setMemberLevel(1);//非会员
            umsMember.setUuid(StringIf.getUUId());
            memberMapper.insertSelective(umsMember);
            umsMember.setPassword(null);
        }else{
            result = commonResult.getMessage();
        }
        return result;
    }

    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        memberCacheService.setAuthCode(telephone, sb.toString());
        return sb.toString();
    }

    @Override
    public void updatePassword(String telephone, String password) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(memberList)) {
            Asserts.fail("该账号不存在");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        handleRedis(umsMember);
        memberCacheService.delMember(umsMember.getId());
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = null;
        try {
            memberDetails = (MemberDetails) auth.getPrincipal();

        }catch (ClassCastException e){
            LOGGER.info("当前没有登录");
            return null;
        }
        return memberDetails.getUmsMember();
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record = new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
        memberCacheService.delMember(id);
    }

    @Override
    public UserDetails loadUserByUsername(String username, Long agentId) {
        UmsMember member = getByUsernameOrPhone(username);
        //如果没有绑定经纪人，绑定该经纪人，重置缓存
        if (agentId != null && member.getAgentId() == null) {
            member.setAgentId(agentId);
            memberMapper.updateByPrimaryKeySelective(member);
            if (member.getIcon() == null || "".equals(member.getIcon())) {
                member.setIcon(MyBatisConfig.getDefaultMemberIcon());
            }
            handleRedis(member);
        }
        if (member != null) {
            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public Map<String, String> login(String username, String password, Integer type, Long agentId) {
//        String token = null;
        Map<String, String> tokenMap = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username,agentId);
            UmsMember user = this.getByUsernameOrPhone(username);
            if (type != null && !type.equals(user.getType())) {
                if (type.equals(0)) {
                    //类型：0->普通用户；1->分销商（乡村经纪人）
                    throw new BadCredentialsException("请选择乡村经纪人进行登录");
                } else {
                    throw new BadCredentialsException("请选择普通用户进行登录");
                }
            }
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
//            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//            SecurityContextHolder.getContext().setAuthentication(authentication);
//            token = jwtTokenUtil.generateToken(userDetails);
//            tokenMap = new HashMap<>();
//            tokenMap.put("token", token);
//            tokenMap.put("tokenHead", tokenHead);
//            String tokenKey = MallSecurityConfig.TOKEN_KEY+username;
//            this.redisService.set(tokenKey,token);
            tokenMap = this.loginMethod(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }

        return tokenMap;
    }

    @Override
    public Map<String, String> loginByOpenId(String openId) {
        Map<String, String> tokenMap = null;
        try{
            UmsMemberExample example = new UmsMemberExample();
            example.createCriteria().andOpenIdEqualTo(openId);
            List<UmsMember> memberList = memberMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(memberList)) {
                UmsMember member = memberList.get(0);
                memberCacheService.setMember(member);
                MemberDetails memberDetails = new MemberDetails(member);
                tokenMap = this.loginMethod(memberDetails);
            }
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return tokenMap;
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    @Override
    public int updateMemberLevel(UmsMember member,Long memberLevelId) {
        UmsMember umsMember = openMember(member, memberLevelId);
        int count = memberMapper.updateByPrimaryKeySelective(umsMember);
        handleRedis(member);
        if (count > 0) {
            return count;
        } else {
            return 0;
        }
    }


    @Override
    public CommonResult<UmsMemberDto> updateMemberInfo(UmsMemberDto umsMemberDto) {
        UmsMember member = getCurrentMember();
        member.setRealName(umsMemberDto.getRealName());
        member.setIcon(umsMemberDto.getIcon());
        member.setGender(umsMemberDto.getGender());
        member.setPhone(umsMemberDto.getPhone());
        member.setGrowPlants(umsMemberDto.getGrowPlants());
        int count = memberMapper.updateByPrimaryKeySelective(member);
        if (count > 0) {
            handleRedis(member);
            return CommonResult.success(umsMemberDto);
        } else {
            return CommonResult.failed();
        }
    }

    @Override
    public CommonResult checkIn() {
        int weekday = DateUtil.getWeek();//当前周几
        //获取当前登录用户的门店id
        UmsMember currentMember = getCurrentMember();
        UmsMember member = memberMapper.selectByPrimaryKey(currentMember.getId());
        Long storeId = member.getStoreId();
        //获取当前用户绑定门店的当前星期的积分
        UmsCheckInIntegrationExample example = new UmsCheckInIntegrationExample();
        example.createCriteria().andStoreIdEqualTo(storeId);
        List<UmsCheckInIntegration> umsCheckInIntegrations = checkInMapper.selectByExample(example);
        if (umsCheckInIntegrations == null || umsCheckInIntegrations.size() == 0) {
            //当前用户绑定门店的当前星期未设置签到积分
            return CommonResult.failed("当前门店未设置签到积分");
        }
        UmsCheckInIntegration umsCheckInIntegration = umsCheckInIntegrations.get(0);
        //把签到获得的积分加到用户的积分上
        int integration = 0;
        switch (weekday) {
            case 1:
                integration = umsCheckInIntegration.getMon();
                break;
            case 2:
                integration = umsCheckInIntegration.getTue();
                break;
            case 3:
                integration = umsCheckInIntegration.getWed();
                break;
            case 4:
                integration = umsCheckInIntegration.getThu();
                break;
            case 5:
                integration = umsCheckInIntegration.getFri();
                break;
            case 6:
                integration = umsCheckInIntegration.getSat();
                break;
            case 7:
                integration = umsCheckInIntegration.getSun();
                break;
        }
        if (member.getIntegration() == null) {
            member.setIntegration(integration);
        } else {
            int newIntegration = member.getIntegration() + integration;
            member.setIntegration(newIntegration);
        }
        //更新用户的签到情况
        String checkIn = member.getCheckIn();//当前用户的签到情况
        checkIn = updateCheckInStatus(checkIn, weekday);
        member.setCheckIn(checkIn);
        int count = memberMapper.updateByPrimaryKey(member);
        handleRedis(member);
        if (count > 0) {
            handleRedis(member);
            //添加用户积分变化记录
            UmsIntegrationChangeHistory umsIntegrationChangeHistory = creatIntegrationChange(member, integration, "签到", 0, 2);
            integrationChangeHistoryMapper.insertSelective(umsIntegrationChangeHistory);
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @Override
    public CommonResult<HashMap> getCheckIn() {
        UmsMember currentMember = getCurrentMember();
        UmsMember member = memberMapper.selectByPrimaryKey(currentMember.getId());
        String checkIn = member.getCheckIn();
        if (checkIn == null || "".equals(checkIn)) {
            checkIn = getNewCheckIn();
        }
        JSONObject jsonObject = JSONObject.parseObject(checkIn);
        UmsCheckInDto dto = JSONObject.toJavaObject(jsonObject, UmsCheckInDto.class);
        Long storeId = member.getStoreId();
        UmsCheckInIntegrationExample example = new UmsCheckInIntegrationExample();
        example.createCriteria().andStoreIdEqualTo(storeId);
        List<UmsCheckInIntegration> umsCheckInIntegrations = checkInMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(umsCheckInIntegrations)) {
            return CommonResult.failed("当前门店未设置签到积分");
        }
        HashMap result = new HashMap();
        result.put("umsCheckInDto", dto);
        result.put("cmsCheckInIntegration", umsCheckInIntegrations.get(0));
        return CommonResult.success(result);
    }

    @Override
    public CommonResult<HashMap> getMemberStore() {
        HashMap result = new HashMap();
        UmsMember member = getCurrentMember();
        if (member.getIcon() == null) {
            member.setIcon(MyBatisConfig.getDefaultMemberIcon());
        }
        if(member==null){
            return CommonResult.success(null);
        }
        //把用户的信息放入dto中
        UmsMemberDto dto = new UmsMemberDto();
        dto.setId(member.getId());//用户id
        dto.setIcon(member.getIcon());//用户头像
        dto.setRealName(member.getRealName());//真实姓名
        dto.setGender(member.getGender());//性别1男，2女
        dto.setPhone(member.getPhone());//手机号
        dto.setType(member.getType());
        dto.setGrowPlants(member.getGrowPlants());//种植作物
        dto.setIntegration(member.getIntegration());
        Integer memberLevel = member.getMemberLevel();//会员类型
        //1为非会员，会员结束时间小于当前时间为非会员
        if (memberLevel == null || memberLevel == 1 || member.getMemberLevelEndTime().before(new Date())) {
            dto.setMemberLevel("非会员");
        } else {
            //根据会员等级id查询会员等级名称
            UmsMemberLevel umsMemberLevel = memberLevelMapper.selectByPrimaryKey(member.getMemberLevelId());
            dto.setMemberLevel(umsMemberLevel.getName());
            dto.setMemberLevelEndTime(member.getMemberLevelEndTime());
        }
        result.put("member", dto);
        if (member.getStoreId() != null) {
            UmsStore store = cacheService.getStore(member.getStoreId());
            if(store.getStatus().equals(0)){
                return CommonResult.failed("该门店已被冻结，请联系管理人员");
            }
//            store.setId(Long.valueOf(8));
            result.put("store", store);
        } else {
            UmsStore store = new UmsStore();
            result.put("store",store);
        }
        return CommonResult.success(result);
    }

    @Override
    public CommonResult<UmsStore> bindStore(Double lat, Double lon) {
        UmsStore nearbyStore = this.portalStoreService.getNearbyStore(lat, lon);
        UmsMember currentMember = this.getCurrentMember();
        CommonResult<UmsStore> result;
        if (nearbyStore != null) {
            currentMember.setStoreId(nearbyStore.getId());
            this.memberMapper.updateByPrimaryKeySelective(currentMember);
            this.memberCacheService.delMember(currentMember.getId());
            result = CommonResult.success(nearbyStore);
            handleRedis(currentMember);
        } else {
            result = CommonResult.failed("您附近没有可用的门店");
        }
        return result;
    }

    /**
     * 校验密码
     *
     * @param password
     * @return
     * @author 孙晓亮
     * @Date 2020年9月11日
     */
    @Override
    public CommonResult verifyPassword(String password) {
        try {
            UmsMember umsMember = getCurrentMember();
            String passwordDb = umsMember.getPassword();
            Boolean flage = passwordEncoder.matches(password, passwordDb);
            if (!flage) {
                return CommonResult.failed("密码不正确");
            }
        } catch (Exception e) {
            LOGGER.warn("校验密码异常:{}", e.getMessage());
            return CommonResult.failed("密码校验失败");
        }

        return CommonResult.success("密码校验成功");
    }

    /**
     * 修改手机号
     *
     * @param authCode 验证码
     * @param phone
     * @return
     * @author 孙晓亮
     * @Date 2020年9月11日
     */
    @Override
    public CommonResult updateMemberPhone(String authCode, String phone) {
        //验证验证码
        CommonResult commonResult = verifyAuthCode(authCode, phone);
        if (commonResult.getCode() != 200) {
            return CommonResult.failed(commonResult.getMessage());
        }
        UmsMember currentMember = getCurrentMember();
//        Long userId = getCurrentMember().getId();//Long.valueOf(16);
        UmsMember umsMember = new UmsMember();
        umsMember.setId(currentMember.getId());
        umsMember.setPhone(phone);
        umsMember.setUsername(phone);
        memberMapper.updateByPrimaryKeySelective(umsMember);
        handleRedis(currentMember);
        memberCacheService.delMember(currentMember.getId());
        return CommonResult.success(null);
    }

    @Override
    public CommonResult<List<UmsMemberLevel>> getMemberInfo(Integer type) {
        UmsMember member = getCurrentMember();
        UmsMemberLevelExample example = new UmsMemberLevelExample();
        example.createCriteria().andStoreIdEqualTo(member.getStoreId()).andTypeEqualTo(type).andLevelNotEqualTo(1);
        List<UmsMemberLevel> umsMemberLevels = memberLevelMapper.selectByExample(example);
        List<UmsMemberLevel> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(umsMemberLevels)) {
            return CommonResult.success(umsMemberLevels);
        } else {
            return CommonResult.success(result);
        }
    }

    @Override
    public List<UmsIntegrationChangeHistory> getIntegrationList() {
        UmsMember member = getCurrentMember();
        UmsIntegrationChangeHistoryExample example = new UmsIntegrationChangeHistoryExample();
        example.createCriteria().andMemberIdEqualTo(member.getId()).andStoreIdEqualTo(member.getStoreId());
        example.setOrderByClause("id desc");
        List<UmsIntegrationChangeHistory> umsIntegrationChangeHistories = integrationChangeHistoryMapper.selectByExample(example);
        List<UmsIntegrationChangeHistory> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(umsIntegrationChangeHistories)) {
            return umsIntegrationChangeHistories;
        } else {
            return result;
        }

    }

    @Override
    public CommonResult setMemberLevelByIntegration(Long memberLevelId) {
        UmsMember currentMember = getCurrentMember();
        UmsMemberLevel umsMemberLevel = memberLevelMapper.selectByPrimaryKey(memberLevelId);
        Integer integrationPrice = umsMemberLevel.getIntegrationPrice();//开通会员需要的积分
        Integer integration = currentMember.getIntegration();//用户的积分
        if(integrationPrice!=null&&integration!=null){
            if(integration >= integrationPrice){
                Integer remainIntegration = integration - integrationPrice;//购买会员剩下的积分
                currentMember.setIntegration(remainIntegration);
                //开通会员
                UmsMember member = openMember(currentMember, memberLevelId);
                member.setIntegration(remainIntegration);//修改积分
                int count = memberMapper.updateByPrimaryKey(member);
                //添加积分变动表记录
                UmsIntegrationChangeHistory umsIntegrationChangeHistory = creatIntegrationChange(member, integrationPrice, "购买会员", 1, 1);
                integrationChangeHistoryMapper.insertSelective(umsIntegrationChangeHistory);
                handleRedis(member);
                return CommonResult.success(count);
            }else{
                return CommonResult.failed("当前积分不足");
            }
        }else{
            return CommonResult.failed("当前积分不足");
        }

    }

    @Override
    public List<UmsMember> getAgentMembers() {
        UmsMember currentMember = this.getCurrentMember();
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria()
                .andAgentIdEqualTo(currentMember.getId())
                .andStoreIdEqualTo(currentMember.getStoreId())
                .andIdNotEqualTo(currentMember.getId());
        List<UmsMember> members = this.memberMapper.selectByExample(example);
        return members;
    }

    @Override
    public CommonResult<Map<String, Object>> getOrderCounts(Integer type) {
        Map<String, Object> result = null;
        UmsMember currentMember = this.memberService.getCurrentMember();
        if (currentMember.getType().equals(0)) {
            //普通用户
            result = this.portalProductDao.getOrderCounts(currentMember.getId(),type);
        }else {
            //经纪人，加一个where条件，replace_order = 0
            result = this.portalProductDao.getOrderCountsByAgent(currentMember.getId(),type);
        }

        OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
        example.createCriteria().andMemberIdEqualTo(currentMember.getId()).andStoreIdEqualTo(currentMember.getStoreId());
        List<OmsOrderReturnApply> omsOrderReturnApplies = returnApplyMapper.selectByExample(example);
        result.put("refund",omsOrderReturnApplies.size());
        return  CommonResult.success(result);
    }

    @Override
    public CommonResult sendAuthCode(String mobile, Integer type) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(mobile);
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if(type.equals(0)){
            //注册
            if(CollectionUtils.isEmpty(umsMembers)){
                return smsService.sendRound6Sms(mobile);
            }else{
                return CommonResult.failed("当前用户已注册");
            }
        }else if (type.equals(1)){
            //忘记密码
            if(!CollectionUtils.isEmpty(umsMembers)){
                //有这个用户
                return smsService.sendRound6Sms(mobile);
            }else{
                //没有这个用户
                return CommonResult.failed("没有当前用户");
            }
        }else{
            return CommonResult.failed();
        }
    }

    @Override
    public CommonResult uploadPositioning(Long memberId, Double lat, Double lon) {
        UmsMember member = memberMapper.selectByPrimaryKey(memberId);
        if (member.getType().equals(0)) {
            return CommonResult.failed();
        }
        UmsAgentCoord coord = new UmsAgentCoord();
        coord.setAgentId(memberId);
        BigDecimal coordLat = new BigDecimal(lat);
        coord.setLat(coordLat);
        BigDecimal coordLon = new BigDecimal(lon);
        coord.setLon(coordLon);
        coord.setStoreId(member.getStoreId());
        //查看当前经纪人在该门店下有多少地址
        UmsAgentCoordExample example = new UmsAgentCoordExample();
        example.createCriteria().andAgentIdEqualTo(memberId).andStoreIdEqualTo(member.getStoreId());
        example.setOrderByClause("id");
        List<UmsAgentCoord> umsAgentCoords = agentCoordMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsAgentCoords) && umsAgentCoords.size() >= 3) {
            //有3条地址，删除第一条
            agentCoordMapper.deleteByPrimaryKey(umsAgentCoords.get(0).getId());
        }
        int insert = agentCoordMapper.insert(coord);
        if (insert > 0) {
            return CommonResult.success(insert);
        } else {
            return CommonResult.failed();
        }
    }

    //对输入的验证码进行校验
    private CommonResult verifyAuthCode(String authCode, String telephone) {
        if (StringUtils.isEmpty(authCode)) {
            return CommonResult.failed("验证码为空");
        }
        return smsService.verifyCode(telephone, authCode);
    }

    /**
     * 根据会员开始时间和会员类别计算会员结束时间
     *
     * @param date          会员开始时间
     * @param memberLevelId 会员类别：2包月会员、3季度会员、4半年会员、5年度会员
     * @return
     */
    private Date getMemberEndTime(Date date, Integer memberLevelId) {
        Date endTime = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (memberLevelId == 2) {
            calendar.add(Calendar.DATE, 30);
        } else if (memberLevelId == 3) {
            calendar.add(Calendar.DATE, 90);
        } else if (memberLevelId == 4) {
            calendar.add(Calendar.DATE, 180);
        } else if (memberLevelId == 5) {
            calendar.add(Calendar.DATE, 360);
        }
        endTime = calendar.getTime();
        return endTime;
    }

    /**
     * 更改用户当天的签到情况
     *
     * @param checkIn
     * @param week
     * @return
     */
    private String updateCheckInStatus(String checkIn, int week) {
        JSONObject jsonObject = JSONObject.parseObject(checkIn);
        UmsCheckInDto dto = JSONObject.toJavaObject(jsonObject, UmsCheckInDto.class);
        switch (week) {
            case 1:
                dto.setMon(1);
                break;
            case 2:
                dto.setTue(1);
                break;
            case 3:
                dto.setWed(1);
                break;
            case 4:
                dto.setThu(1);
                break;
            case 5:
                dto.setFri(1);
                break;
            case 6:
                dto.setSat(1);
                break;
            case 7:
                dto.setSun(1);
                break;
        }
        jsonObject = (JSONObject) JSONObject.toJSON(dto);
        checkIn = jsonObject.toString();
        return checkIn;
    }

    /**
     * 新用户checkIn字段为空，根据当前周几重置
     *
     * @return
     */
    private String getNewCheckIn() {
        UmsCheckInDto dto;
        int week = DateUtil.getWeek();
        switch (week) {
            case 1:
                dto = new UmsCheckInDto(0, 2, 2, 2, 2, 2, 2);
                break;
            case 2:
                dto = new UmsCheckInDto(2, 0, 2, 2, 2, 2, 2);
                break;
            case 3:
                dto = new UmsCheckInDto(2, 2, 0, 2, 2, 2, 2);
                break;
            case 4:
                dto = new UmsCheckInDto(2, 2, 2, 0, 2, 2, 2);
                break;
            case 5:
                dto = new UmsCheckInDto(2, 2, 2, 2, 0, 2, 2);
                break;
            case 6:
                dto = new UmsCheckInDto(2, 2, 2, 2, 2, 0, 2);
                break;
            case 7:
                dto = new UmsCheckInDto(2, 2, 2, 2, 2, 2, 0);
                break;
            default:
                dto = new UmsCheckInDto();
        }
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(dto);
        String checkIn = jsonObject.toString();
        return checkIn;
    }

    /**
     * 更新用户缓存
     *
     * @param member
     */
    @Override
    public void handleRedis(UmsMember member) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_MEMBER + ":" + member.getUsername();
        Boolean del = redisService.del(key);
        UmsMember ums = memberMapper.selectByPrimaryKey(member.getId());
        redisService.set(key, ums);
    }

    /**
     * 生成一条积分变动记录
     * @param member 当前用户
     * @param integration 积分
     * @param operateNote 备注
     * @param changeType 改动类型1增加；0减少
     * @param sourceType 获得积分方式
     * @return
     */
    @Override
    public UmsIntegrationChangeHistory creatIntegrationChange(UmsMember member,Integer integration,String operateNote,Integer changeType,Integer sourceType){
        UmsIntegrationChangeHistory umsIntegrationChangeHistory = new UmsIntegrationChangeHistory();
        umsIntegrationChangeHistory.setCreateTime(new Date());
        umsIntegrationChangeHistory.setMemberId(member.getId());
        umsIntegrationChangeHistory.setChangeCount(integration);
        umsIntegrationChangeHistory.setChangeType(changeType);
        umsIntegrationChangeHistory.setOperateMan(member.getUsername());
        umsIntegrationChangeHistory.setSourceType(sourceType);
        umsIntegrationChangeHistory.setOperateNote(operateNote);
        umsIntegrationChangeHistory.setMemberUserName(member.getUsername());
        umsIntegrationChangeHistory.setStoreId(member.getStoreId());
        umsIntegrationChangeHistory.setMemberUserId(member.getId());
        return umsIntegrationChangeHistory;
    }

    /**
     * 开通会员的方法
     * 传来会员id，把当前用户改为会员后返回
     * @param currentMember
     * @param memberLevelId
     * @return
     */
    private UmsMember openMember(UmsMember currentMember,Long memberLevelId) {
        //新增会员变动表记录
        UmsMemberLevelChangeHistory changeHistory = new UmsMemberLevelChangeHistory();
        changeHistory.setMemberId(currentMember.getId());//用户id
        changeHistory.setStoreId(currentMember.getStoreId());//门店id
        changeHistory.setCreateTime(new Date());//创建时间
        changeHistory.setUpdateBeforeMemberLevelId(currentMember.getMemberLevelId());//更改前会员等级
        changeHistory.setUpdateAfterMemberLevelId(memberLevelId);//更改后会员等级
        changeHistory.setUpdateBeforeMemberEndTime(currentMember.getMemberLevelEndTime());
        //会员等级
        UmsMemberLevel umsMemberLevel = memberLevelMapper.selectByPrimaryKey(memberLevelId);
        int memberLevel = umsMemberLevel.getLevel();
        Date memberEndTime;//会员结束时间
        Date memberLevelEndTime = currentMember.getMemberLevelEndTime();
        if (memberLevelEndTime != null && memberLevelEndTime.after(new Date())) {
            //会员结束日期大于当前日期，为续费会员
            memberEndTime = getMemberEndTime(memberLevelEndTime, memberLevel);
            changeHistory.setMemberStartTime(currentMember.getMemberLevelStartTime());
            changeHistory.setOpenType(1);
        } else {
            //会员开通
            //会员开始日期
            currentMember.setMemberLevelStartTime(new Date());
            memberEndTime = getMemberEndTime(new Date(), memberLevel);
            changeHistory.setMemberStartTime(new Date());
            changeHistory.setOpenType(0);
        }
        //会员结束日期
        currentMember.setMemberLevelEndTime(memberEndTime);
        currentMember.setMemberLevelId(memberLevelId);
        currentMember.setMemberLevel(memberLevel);
        changeHistory.setBuyType(umsMemberLevel.getType());//购买类型
        if (umsMemberLevel.getType().equals(0)) {//类型0积分兑换；1花钱买
            changeHistory.setIntegrationPrice(umsMemberLevel.getIntegrationPrice());
            changeHistory.setMoneyPrice(new BigDecimal(0));
        }else {
            changeHistory.setMoneyPrice(umsMemberLevel.getPrice());
            changeHistory.setIntegrationPrice(0);
        }
        changeHistory.setUpdateAfterMemberEndTime(memberEndTime);
        changeHistoryMapper.insert(changeHistory);
        return currentMember;
    }

    /**
     * 登录的公共方法
     * @param userDetails
     * @return
     */
    private Map<String, String> loginMethod(UserDetails userDetails){
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        String tokenKey = MallSecurityConfig.TOKEN_KEY+userDetails.getUsername();
        this.redisService.set(tokenKey,token);
        return tokenMap;
    }
}
